from datetime import datetime
from config import dbCon
from role import role
class actor:
    def __init__(self, id=0, loginEmail=None, password=None, status='A', lastLogin=None):
        self.id = id
        self.loginEmail = loginEmail
        self.password = password
        self.status = status
        self.lastLogin = lastLogin
    
    def addUser(self, actor):
        if actor.lastLogin and actor.loginEmail:
            #handle the excetpion
            dbCon.insert('user',
                  user_login=actor.loginEmail,
                  user_password=actor.password,
                  user_status='A',
                  user_register_date=datetime.utcnow())
    def addRoleToUser(self, role):
        if role.id:
            dbCon.insert('user_role_link',
                         user_id=self.id,
                         role_id=role.id,
                         role_status='V')
            
    
#    def updateRoleStatus(self, roleId, userId, status):
#        if roleId and userId and status:
#            dbCon.update('user_role_link',
#                         role_status=status,
#                         where='user_id=$v_user_id and role_id=$v_role_id',
#                         vars={v_user_id : userId, v_role_id : roleId})
    
    def getUser(self, loginEmail=None, loginId=None):
        if loginEmail:
            dbCon.select('user',
                         what='')
            
    def setRole(self, role):
        self.role = role
            
    def login(self, loginEmail, password):
        if loginEmail and password:
            result = dbCon.select('user t1 join user_role_link t2 on t1.user_id = t2.user_id join role t3 on t3.role_id',
                                 what='t1.user_id, t1.user_login, t1.user_status, t1.user_last_login, t1.user_register_date, t3.role_id, t3.role_name',
                                 where="t1.user_login = $loginEmail and t1.user_password=$password and t1.status='A' and t3.status='A'",
                                 vars={loginEmal:loginEmail, password:password}
                                 )
        if Len(result)>0:
            result = result[0]
            self =  actor(result['user_id'], result['user_login'], None, result['user_status'])
            setRole(role(result['role_id'], result['role_name']))